<template>
  <div class="app-container">

    <div style="margin-right: 20px; margin-bottom: 20px;">
      <el-radio-group v-model="buttonType" size="medium" @input="changeButtonType">
        <el-radio-button label="洗车订单" ></el-radio-button>
        <el-radio-button label="维修订单"></el-radio-button>
        <el-radio-button label="保养订单"></el-radio-button>
      </el-radio-group>
    </div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="buyers">
        <el-input
          v-model="queryParams.buyers"
          placeholder="请输入用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="全部">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="payTime">
        <el-date-picker
          v-model="queryParams.TheTime"
          type="daterange"
          range-separator="至"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="orderDetailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderDetailsId" />
      <el-table-column label="服务名称" align="center" prop="serviceDetails" >
        <template slot-scope="scope">
          <span>{{scope.row.serviceDetails.name}}</span>
          <span v-if="scope.row.serviceDetails.serviceClassification != null">; </span><br>
          <span v-if="scope.row.serviceDetails.serviceClassification==1">维修</span>
          <span v-if="scope.row.serviceDetails.serviceClassification==2">保养</span>
          <span v-if="scope.row.serviceDetails.serviceClassification==3">洗车</span>
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center" prop="buyers" >
        <template slot-scope="scope">
          <span>{{ scope.row.user.userName }} </span><br>
          <span>{{ scope.row.user.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家" align="center" prop="merchant" >
        <template slot-scope="scope">
          <span>{{scope.row.merchant.merchantName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="payPrice" >
        <template slot-scope="scope">
          <span>原 价：{{scope.row.prePrice}}</span><br>
          <span>优 惠：{{scope.row.coupons.preferentialMoney}}</span><br>
          <span v-if="scope.row.orderStatus !== 1 ">实 付：</span>
          <span v-else>应 付：</span>
          <span>{{scope.row.payPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus" >
      <!--   （订单状态：1待支付、2待使用、3已取消、4已退款、5已完成）   -->
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderStatus === 1" >待支付</el-tag>
          <el-tag v-if="scope.row.orderStatus === 5" type="success">已完成</el-tag>
          <el-tag v-if="scope.row.orderStatus === 2" type="info">待使用</el-tag>
          <el-tag v-if="scope.row.orderStatus === 4" type="warning">已退款</el-tag>
          <el-tag v-if="scope.row.orderStatus === 3" type="danger">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改洗车订单对话框 -->
    <el-dialog :title="title" visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务id" prop="serviceId">
          <el-input v-model="form.serviceId" placeholder="请输入服务id" />
        </el-form-item>
        <el-form-item label="核销码" prop="verCode">
          <el-input v-model="form.verCode" placeholder="请输入核销码" />
        </el-form-item>
        <el-form-item label="核销码图片" prop="verImage">
          <image-upload v-model="form.verImage"/>
        </el-form-item>
        <el-form-item label="用户" prop="buyers">
          <el-input v-model="form.buyers" placeholder="请输入用户" />
        </el-form-item>
        <el-form-item label="商家" prop="seller">
          <el-input v-model="form.seller" placeholder="请输入商家" />
        </el-form-item>
        <el-form-item label="用户车辆" prop="userCar">
          <el-input v-model="form.userCar" placeholder="请输入用户车辆" />
        </el-form-item>
        <el-form-item label="原价" prop="prePrice">
          <el-input v-model="form.prePrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="实付价格" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入实付价格" />
        </el-form-item>
        <el-form-item label="预约时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券id" prop="couponId">
          <el-input v-model="form.couponId" placeholder="请输入优惠券id" />
        </el-form-item>
        <el-form-item label="支付状态" prop="paytus">
          <el-input v-model="form.paytus" placeholder="请输入支付状态" />
        </el-form-item>
        <el-form-item label="下单时间" prop="updateTime">
          <el-date-picker clearable
            v-model="form.payTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否评价" prop="evaluate">
          <el-input v-model="form.evaluate" placeholder="请输入是否评价" />
        </el-form-item>
        <el-form-item label="逻辑删除，0正常1删除" prop="del">
          <el-input v-model="form.del" placeholder="请输入逻辑删除，0正常1删除" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog :title="title" :visible.sync="openDetails" width="800px" append-to-body>
      <el-form :model="form" ref="ruleForm" label-width="130px" :inline="true">
        <el-form-item label="订单编号：" prop="orderDetailsId" style="background-color: #eeeeee;">
          <div class="detailsItem1"><span>{{ form.orderDetailsId }}</span></div>
        </el-form-item>
        <el-form-item label="服务编号：" prop="serviceId" style="background-color: #eeeeee;">
          <div class="detailsItem1"><span>{{ form.serviceId }}</span></div>
        </el-form-item>
        <el-form-item label="核销码：" prop="verCode" style="background-color: #eeeeee;">
          <div class="detailsItem1"><span>{{ form.verCode }}</span></div>
        </el-form-item>
        <el-form-item label="商家名称：" prop="seller" style="background-color: #eeeeee;">
          <div class="detailsItem1"><span>{{ form.merchant.merchantName }}</span></div>
        </el-form-item>
        <el-form-item label="买家：" prop="user" style="background-color: #eeeeee;">
          <div class="detailsItem1">
            <span>{{ form.user.userName }} </span>
            <span>{{ form.user.phone }}</span>
          </div>
        </el-form-item>
        <el-form-item label="订单状态：" prop="orderStatus" style="background-color: #eeeeee;">
          <div class="detailsItem1">
            <span v-if="form.orderStatus === 1" >待支付</span>
            <span v-if="form.orderStatus === 5" type="success">已完成</span>
            <span v-if="form.orderStatus === 2" type="info">待使用</span>
            <span v-if="form.orderStatus === 4" type="warning">已退款</span>
            <span v-if="form.orderStatus === 3" type="danger">已取消</span>
          </div>
        </el-form-item>
        <el-form-item label="下单时间：" prop="createTime" style="background-color: #eeeeee;">
          <div class="detailsItem1"><span>{{ form.createTime }}</span></div>
        </el-form-item>
        <el-form-item label="预约时间：" prop="orderTime" style="background-color: #eeeeee;">
          <div class="detailsItem1"><span>{{ form.orderTime }}</span></div>
        </el-form-item>
        <el-form-item label="原价：" prop="prePrice" style="background-color: #eeeeee;">
          <div class="detailsItem2"><span>{{ form.prePrice }}</span></div>
        </el-form-item>
        <el-form-item label="优惠价：" prop="couponId" style="background-color: #eeeeee;">
          <div class="detailsItem2"><span>{{ form.coupons.preferentialMoney }}</span></div>
        </el-form-item>
        <el-form-item label="实付金额：" prop="payPrice" style="background-color: #eeeeee;">
          <div class="detailsItem2"><span>{{ form.payPrice }}</span></div>
        </el-form-item>
        <el-form-item label="服务内容：" prop="serviceDetails" style="background-color: #eeeeee;">
          <div class="detailsItem2" ><span>{{ form.serviceDetails.serviceIntroduction }}</span></div>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { listOrderDetails, getOrderDetails, delOrderDetails, addOrderDetails, updateOrderDetails } from "@/api/carService/orderDetails";

export default {
  name: "OrderDetails",
  data() {
    return {
      // buttonType 洗车订单、维修订单、保养订单
      buttonType: '洗车订单',

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 洗车订单表格数据
      orderDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看订单详情
      openDetails: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceId: null,
        verCode: null,
        verImage: null,
        buyers: null,
        seller: null,
        userCar: null,
        prePrice: null,
        payPrice: null,
        orderStatus: null,
        orderTime: null,
        couponId: null,
        paytus: null,
        updateTime: null,
        evaluate: null,
        del: null,

        TheTime: ['',''],
        startTime: null,
        endTime: null,
        serviceType: 3, // 服务类型
        district: null,// 区地址 查询参数

        user: {
          userName: null,
          phone: null,
        }

      },

      // 订单状态选择（订单状态：1待支付、2待使用、3已取消、4已退款、5已完成）
      options: [{
        value: null, label: '全部'
      }, {
        value: 1, label: '待支付'
      }, {
        value: 2, label: '待使用'
      }, {
        value: 3, label: '已取消'
      }, {
        value: 4, label: '已退款'
      }, {
        value: 5, label: '已完成'
      }],

      // 表单参数
      form: {
        serviceDetails: {
          serviceIntroduction: null,
        },
        user: {
          userName: null,
          phone: null,
        },
        coupons: {
          preferentialMoney: null,
        },
        merchant: {
          merchantName: null,
        },
      },
      // 表单校验
      rules: {
        orderTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "下单时间不能为空", trigger: "blur" }
        ],
        payTime: [
          { required: true, message: "支付时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    const params = this.$route.params;
    console.log(params);
    // buttonType 洗车订单、维修订单、保养订单
    if (params.service=='车辆维修'){
      this. buttonType='维修订单';
      this.queryParams.serviceType=1;
    }else  if (params.service=='洗车服务'){
      this. buttonType='洗车订单';
      this.queryParams.serviceType=3;
    }else  if (params.service=='车辆保养'){
      this. buttonType='保养订单';
      this.queryParams.serviceType=2;
    }
    if (params.time!=null){
      this.queryParams.TheTime = params.time;
    }
    if (params.address!=null){
      console.log(params.address);
       /* merchant: {  // 商户对象 查询字段
          province: null, // 省
          city: null, // 市
          district: null, // 区
        },*/
       this.queryParams.district = params.address;
       console.log(this.queryParams);

    }
    this.getList();
  },
  methods: {
    /** 查询洗车订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.startTime = this.queryParams.TheTime[0];
      this.queryParams.endTime = this.queryParams.TheTime[1];
      if(this.queryParams.TheTime[0] === '') {
        this.queryParams.startTime = null;
      }
      if(this.queryParams.TheTime[1] === '') {
        this.queryParams.endTime = null;
      }
      listOrderDetails(this.queryParams).then(response => {
        this.orderDetailsList = response.rows;
        console.log(response)
        this.total = response.total;
        this.loading = false;
        this.getPriceResult();
      });
    },
    /** 点击修改订单类型："3"洗车订单 , "1"维修订单 , "2"保养订单 */
    changeButtonType(){
      // 默认 洗车订单
      this.queryParams.serviceType = 3;
      switch (this.buttonType) {
        case "维修订单":
          this.queryParams.serviceType = 1;
          break;
        case "保养订单":
          this.queryParams.serviceType = 2;
          break;
      }
      this.getList();
    },

    /** 计算价格， 添加优惠券之后的价格，满减券  打折券 */
    getPriceResult(){
      for(let i = 0; i < this.orderDetailsList.length; i++){
        let prePrice = this.orderDetailsList[i].prePrice; // 原价
        let payPrice = prePrice; // 实付价格

        let coupons = this.orderDetailsList[i].coupons; // 优惠券
        // 如果是打折券
        if(coupons.discount !== null){
          payPrice = prePrice * coupons.discount * 0.01;
          coupons.preferentialMoney = prePrice - payPrice; // 修改优惠金额
          console.log(payPrice)
        }
        // 满减券
        else if(coupons.preferentialMoney !== null){
          payPrice = prePrice - coupons.preferentialMoney;
        }

        this.orderDetailsList[i].payPrice = payPrice;
        this.orderDetailsList[i].coupons = coupons;
        console.log(payPrice)
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderDetailsId: null,
        serviceId: null,
        verCode: null,
        verImage: null,
        buyers: null,
        seller: null,
        userCar: null,
        prePrice: null,
        payPrice: null,
        status: null,
        orderTime: null,
        createTime: null,
        couponId: null,
        paytus: null,
        updateTime: null,
        evaluate: null,
        del: null,
        serviceDetails: {},
        user: {},
        coupons: {},
        merchant: {},
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.startTime = null;
      this.queryParams.endTime = null;
      this.queryParams.TheTime = ['',''];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderDetailsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加洗车订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderDetailsId = row.orderDetailsId || this.ids
      getOrderDetails(orderDetailsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改洗车订单";
      });
    },
    // 查看订单详情
    handleDetails(row){
      this.reset();
      const orderDetailsId = row.orderDetailsId || this.ids
      getOrderDetails(orderDetailsId).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.openDetails = true;
        this.title = "查看订单详情：";

        let prePrice = this.form.prePrice; // 原价
        let payPrice = prePrice; // 实付价格
        let coupons = this.form.coupons; // 优惠券
        // 如果是打折券
        if(coupons.discount !== null){
          payPrice = prePrice * coupons.discount * 0.01;
          coupons.preferentialMoney = prePrice - payPrice; // 修改优惠金额
          console.log(1)
        }
        // 满减券
        else if(coupons.preferentialMoney !== null){
          payPrice = prePrice - coupons.preferentialMoney;
          console.log(2)
        }
        this.form.payPrice = payPrice;
        this.form.coupons = coupons;
        console.log(payPrice)
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderDetailsId != null) {
            updateOrderDetails(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderDetails(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderDetailsIds = row.orderDetailsId || this.ids;
      this.$modal.confirm('是否确认删除洗车订单编号为"' + orderDetailsIds + '"的数据项？').then(function() {
        return delOrderDetails(orderDetailsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('carService/orderDetails/export', {
        ...this.queryParams
      }, `orderDetails_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss">
  .detailsItem1{
    background-color: #fff;
    width: 230px;
    height: 40px;
    border: 1px solid #ddd;
    padding-left: 10px;
  }
  .detailsItem2{
    background-color: #fff;
    width: 600px;
    height: 40px;
    border: 1px solid #ddd;
    padding-left: 10px;
  }
</style>
